﻿using AdminSystem.Application.Commands.LoginCommands;
using AdminSystem.Domain.Entities;
using AdminSystem.EntityFramworkCore;
using AdminSystem.Repositories.Interfaces;
using AdminSystem.Application.Dtos;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminSystem.Application.CommandHandlers.LoginCommandHandlers
{
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<List<UserDTO>>>
    {
        private readonly IBaseRepositories<User> userBase;
        private readonly IBaseRepositories<Role> roleBase;
        public LoginQueryCommandHandler(IBaseRepositories<User> userBase, IBaseRepositories<Role> roleBase)
        {
            this.userBase = userBase;
            this.roleBase = roleBase;
        }
        public async Task<APIResult<List<UserDTO>>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<UserDTO>> result = new APIResult<List<UserDTO>>();
            result.Code = ResultCode.登录成功;
            result.Message = ResultCode.登录成功.ToString();
            try
            {
                var users = await userBase.GetAll();
                var roles = await roleBase.GetAll();
                var user = from a in users
                           join b in roles on a.RoleId equals b.RoleId
                           where a.UserName == request.UserName
                           select new UserDTO
                           {
                               UserId = a.UserId,
                               UserName = a.UserName,
                               UserPass = a.UserPass,
                               UserNickname = a.UserNickname,
                               RoleId = a.RoleId,
                               RoleName = b.RoleName
                           };
                var entity = user.FirstOrDefault();
                if (entity == null)
                {
                    throw new Exception("用户名不存在");
                }
                if (entity.UserPass != request.UserPass)
                {
                    throw new Exception("用户名和密码不匹配");
                }
                
                result.Data = new List<UserDTO> { new UserDTO { UserId = entity.UserId, UserName = entity.UserName, UserPass = entity.UserPass, UserNickname = entity.UserNickname, RoleId = entity.RoleId, RoleName = entity.RoleName } };
                //return result;               
            }
            catch (Exception exp)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "," + exp.Message;
            }
            //return result;
            return result;
        }
    }
}
